from typing import Union

from requests import Response

from response_intrerface import ResponseHandler, StreamingResponse, ResponseManager


class ChocolateyResponseHandler(ResponseHandler):
    def handle(self, host: str, response: Response) -> Union[bytes, str, Response]:
        if not self.is_text(response):
            return response
        
        content = response.text

        host_url = f'http://{host}/proxy/choco'

        # 把响应中
        # <link rel="next"
        # href="http://community.chocolatey.org/api/v2/Search?searchTerm='vscode'&amp;targetFramework=''&amp;includePrerelease=false&amp;$filter=IsLatestVersion&amp;$orderby=Id&amp;$top=30&amp;$skiptoken='zephyr-ide'"
        # />
        # 的内容 <link rel="next" href="http://community.chocolatey.org/api/v2 替换成当前服务的地址
        x =  content.replace(
            '<link rel="next" href="http://community.chocolatey.org/api/v2',
            f'<link rel="next" href="{host_url}'
        )

        x = x.replace(
            'https://community.chocolatey.org/api/v2/package',
            f'{host_url}/package',
        )

        # print(x)
        return x


class PythonResponseHandler(ResponseHandler):
    def handle(self, host: str, response: Response) -> Union[bytes, str, Response]:
        if not self.is_text(response):
            return response
        
        content = response.text

        host_url = f'http://{host}/proxy/python'

        print(content)
        return content



def init_response_handlers():
    # ResponseManager.register('/proxy/choco/', ChocolateyResponseHandler())
    ResponseManager.register('/proxy/python/', PythonResponseHandler())
